import React from 'react';
import {Table, Row, Col, Form, Input, Icon, InputNumber, Radio, DatePicker, Select, Upload, Button, Switch, Modal, Popconfirm, Tabs, message, Steps} from 'antd';
const R = require('ramda');

const Step = Steps.Step;
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;
const Dragger = Upload.Dragger;
const RadioGroup = Radio.Group;
import SingleDragger from '../../../components/commons/SingleDragger'
import OperatorConstant from "../../../utils/OperatorConstant";


export default Form.create({wrappedComponentRef: true})(class EditBusinessagreement extends React.Component {
	constructor(props) {
		super(props);
        this.state = {
            open: false,
            disabled: true,
            type: "",
            require_memo:true,
            require_other:true,
            saveLoading: false,
            submitLoading: false,


        }
	}


    checkFkManager(){
	    let bool=!R.isNil(this.props.fkManager)||(this.state.type == OperatorConstant.approval)||(this.state.type==OperatorConstant.saveAndApproval);
	    return bool;
    }

    handleResetFields = () => {
        this.props.form.resetFields();
        if(this.refs.businessAgreementUrl)this.refs.businessAgreementUrl.resetUpload();

    }

    handleCancel = () => {
        this.handleResetFields();
        this.setState({open:false,require_other:true,require_memo:true})

        this.props.dispatch({
            type: 'businessAgreement/setDataSource',
            payload: {
                dataSource: "",
            }
        });

        this.props.dispatch({
            type: 'businessAgreement/setNode',
            payload: {
                node: {},
            }
        });
    }

    handleOpen = (type, disable) => {
        this.state.type = type;

        if(!R.isNil(disable)){
            this.state.disabled = disable;
        }
        this.setState({open: true});

    }
    handleConfirm = (method) => {


        if (this.state.type == OperatorConstant.add || this.state.type == OperatorConstant.edit || OperatorConstant.saveAndApproval == this.state.type) {
            let url = this.refs.businessAgreementUrl.getUrl();
            if (R.isNil(url) || R.isEmpty(url)) {
                message.error("请先上传业务合同");
                return;
            }
        }

        if(!this.checkFkManager()){
            message.error("风控经理未分配");
            return;
        }

        this.props.form.validateFields((errors, values) => {


            let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource;
            if (errors) return;

            if(this.state.type == OperatorConstant.view){
                return;
            }

            if(this.state.type == OperatorConstant.approval){
                if(this.state.disabled == true){
                    return;
                }
                this.setState({ submitLoading: true });
                this.props.dispatch({
                    type: "businessAgreement/agreementApproval",
                    payload: {
                        id : dataSource.id,
                        approvalresult: values.approvalresult ,
                        approvalmemo: values.approvalmemo ,
                        onSuccess: () => this.repetition(),
                        onFail: () => this.setState({submitLoading: false})
                    }
                })
            }else{
                let type = "";
                if (this.state.type == OperatorConstant.add) {
                    type = "businessAgreement/addAgreement";


                } else if (this.state.type == OperatorConstant.edit || this.state.type == OperatorConstant.saveAndApproval) {
                    type = "businessAgreement/updateAgreement";

                }

                let  payload= {
                    method: method,
                    cstid : R.isNil(dataSource.cstid) ? this.props.cstid: dataSource.cstid,
                    id : dataSource.id,
                    title: values.title,
                    content: values.content,
                    url: this.refs.businessAgreementUrl.getUrl(),


                    onSuccess: () => this.repetition(),
                    onFail: () => this.setState({submitLoading: false})
                };

                if(OperatorConstant.saveAndApproval ==  method && (this.state.type == OperatorConstant.edit || this.state.type == OperatorConstant.saveAndApproval)){
                    payload.status = 2;
                }

                this.props.dispatch({
                    type: type,
                    payload: payload,
                    onSuccess: () => this.repetition(),
                    onFail: () => this.setState({submitLoading: false})
                })
            }


        })
    }

    repetition=()=>{
	    this.props.handleSearch();
        this.setState({submitLoading: false});
        this.handleCancel();
   }


    handleSelect=(value)=>{
        this.props.form.setFields({
            approvalmemo:{errors:null},
        });
        if(value==2){
            this.state.require_other=true;
            this.state.require_memo=false;
        }else{
            this.state.require_other=false;
            this.state.require_memo=true;
        }
    };



    columns = [
        {title: '任务id', dataIndex: 'taskid', key: 'taskid'},
        {title: '节点', dataIndex: 'nodeid', key: 'nodeid'},
        {title: '审核人员', dataIndex: 'creatorName', key: 'creatorName'},
        {title: '审核意见', dataIndex: 'memo', key: 'memo'},
        {title: '提交时间', dataIndex: 'createtime', key: 'createtime'},
        ];


	render() {
		const { getFieldDecorator } = this.props.form;
        const formItemLayout = {labelCol: { xs: {span: 8}, sm: {span: 6}}, wrapperCol: {xs: {span: 15}, sm: {span: 14}}};
        let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource;

        let businessAgreementUrl =  R.isNil(dataSource.url) ? "" : dataSource.url;



        let footer = [];


        if(this.state.type == OperatorConstant.approval ){
            if(this.state.disabled == false){
                footer.push( <Button key="submit" size="large" loading={this.state.submitLoading} disabled={this.state.disabled || this.state.saveLoading|| this.state.type == OperatorConstant.view} onClick={this.handleConfirm.bind(this, OperatorConstant.approval)}
                >审核</Button>);
            }

        }else if(this.state.type != OperatorConstant.view ){

            if(this.state.type == OperatorConstant.add || this.state.type == OperatorConstant.edit){
                footer.push( <Button key="submit" size="large" loading={this.state.submitLoading} disabled={this.props.disabled} onClick={this.handleConfirm.bind(this, "save")}
                >保存</Button>);
            }

            if((this.state.type == OperatorConstant.edit || this.state.type == OperatorConstant.saveAndApproval || this.state.type == OperatorConstant.add)&&this.checkFkManager()){
                footer.push( <Button key="saveAndApproval" size="large" loading={this.state.submitLoading} disabled={this.props.disabled} onClick={this.handleConfirm.bind(this, OperatorConstant.saveAndApproval)}
                >保存并提交审核</Button>);

            }

        }

        footer.push( <Button key="cancel" size="large" onClick={this.handleCancel.bind(this, true)}>取消</Button> );


        let pagination = {
            showTotal: total => `共 ${total} 条数据`,
            pageSize: this.props.approvalPage.size,
            total: this.props.approvalPage.totalRow,
            showSizeChanger: true,
            current: this.props.approvalPage.page,
            onShowSizeChange: (current, size) => {
                let newPage = this.props.approvalPage;
                newPage.size = size;
                newPage.page = 1;
                this.props.dispatch({
                    type: 'businessAgreement/getAgreementApprovalList',
                    payload: {
                        id: R.isNil(dataSource.id) ? "" : dataSource.id,
                        page: newPage,
                        cstId: this.props.cstid
                    }
                });
            },
            onChange: (pageNumber, pageSize) => {
                let newPage = this.props.approvalPage;
                newPage.page = pageNumber;
                this.props.dispatch({
                    type: 'businessAgreement/getAgreementApprovalList',
                    payload: {
                        id: R.isNil(dataSource.id) ? "" : dataSource.id,
                        page: newPage,
                        cstId: this.props.cstid
                    }
                });
            }
        }

        let node = this.props.node;
        let nodename =""
        let step = "";
        let role =[];
        let isbypass = node.isbypass;
        let approvalDisable = true;


        //当前用户拥有的角色
        if(!R.isNil(node.roles) && !R.isEmpty(node.roles)){
            for(let i=0; i< node.roles.length; i++){
                role.push(node.roles[i].roleId);
            }
        }


        //越级审核
        if(isbypass == 1){
            let approvalRoles =[];

            //审核链角色
            let approvalRole = node.approvalRole;

            let flag = false;
            if(!R.isNil(node.list) && !R.isEmpty(node.list)){
                if(approvalRole == node.list[i].role){
                    flag = true;
                }

                if(flag && R.isNil(node.list[i].role) && R.isEmpty(node.list[i].role) ){
                    approvalRoles.push(node.list[i].role);
                }
            }


            approvalDisable = this.state.disabled || this.state.type == OperatorConstant.view || R.isNil(node.approvalRole) || !R.intersection(approvalRoles, approvalRole);


        }else{

            if(!R.isNil(node.list) && !R.isEmpty(node.list)){
                let currentNode = 0;

                for(let i=0; i< node.list.length; i++){
                    if(node.nodeName == node.list[i].name){
                        currentNode = i;
                        nodename += "：当前审核节点【" + node.list[i].name + "】";
                        break;
                    }

                }

                step = <Steps current={currentNode} style={{width: '95%'}}>
                    {
                        R.isNil(node.list) || R.isEmpty(node.list)  ? <Step title=""></Step>
                            :
                            node.list.map(item => {
                                return (<Step title={item.name}></Step>);
                            })
                    }
                </Steps>
            }

            approvalDisable = this.state.disabled || this.state.type == OperatorConstant.view || R.isNil(node.approvalRole) || !R.contains(node.approvalRole, role);
        }

        let disable = this.props.disabled || this.state.type == OperatorConstant.view || this.state.type == OperatorConstant.approval;

        return (
            <Modal maskClosable={false} footer={footer} visible={this.state.open} title={ R.isEmpty(step) ? "业务合同" : step } width={900} wrapClassName="vertical-center-modal"
                   onCancel={this.handleCancel} >

                <Form>

                    <div>

                        <span style = {{color: 'red', marginLeft: '40px', fontSize: 13 , }}>注意事项:(增加的业务合同费用应该和代理协议的费用一致!!!)</span>

                        <Row style = {{marginTop: '20px' }}>
                            <Col span={24}>
                                <FormItem {...formItemLayout} label="合同标题" hasFeedback>
                                    {getFieldDecorator('title', {
                                        rules: [{
                                            required: true, message: '请输入合同标题'
                                        }],
                                        initialValue: dataSource.title
                                    })(
                                        <Input maxLength="200" disabled={disable}/>
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={24}>
                                <FormItem {...formItemLayout} label="合同备注" hasFeedback>
                                    {getFieldDecorator('content', {
                                        rules: [{
                                            required: true, message: '请输入合同备注'
                                        }],
                                        initialValue: dataSource.content
                                    })(
                                        <Input.TextArea rows={4} maxLength="255" disabled={disable} />
                                    )}
                                </FormItem>
                            </Col>
                        </Row>
                    </div>

                    <Tabs tabPosition={'top'}>
                        <TabPane tab="附件" key="1">
                            <Row>
                                <Col span={24}>
                                    <FormItem {...formItemLayout} label={<span className="ant-form-item-required">附件(业务合同)</span>} hasFeedback>
                                        <SingleDragger  url={businessAgreementUrl}  ref="businessAgreementUrl" dataSource={dataSource}
                                                        disabled={disable}/>
                                    </FormItem>
                                </Col>
                            </Row>

                        </TabPane>
                    </Tabs>



                    {this.state.type == OperatorConstant.approval || this.state.type == OperatorConstant.saveAndApproval?
                        <Tabs tabPosition={'top'}>
                            <TabPane tab={"审核" +nodename} key="1">
                                <Row>
                                    <Col span={12}>
                                        <FormItem
                                            {...formItemLayout}
                                            label="请选择审核结果"
                                            hasFeedback
                                        >
                                            {getFieldDecorator('approvalresult', {
                                                rules: [{
                                                    required: this.state.type == OperatorConstant.saveAndApproval ? false : true, message: '请选择审核结果！',
                                                }],
                                                initialValue: R.isNil(dataSource.status) || !R.contains(dataSource.status, ["3", "4", ""]) ? "" : dataSource.status
                                            })(
                                                        <Select disabled={approvalDisable} onChange={this.handleSelect.bind(this)}>
                                                            <Option value="2">审核通过</Option>
                                                            <Option value="3">审核不通过</Option>
                                                        </Select>
                                            )}
                                        </FormItem>
                                    </Col>
                                    <Col span={12}>
                                        <FormItem
                                            {...formItemLayout}
                                            label="备注"
                                            hasFeedback
                                        >
                                            {getFieldDecorator('approvalmemo', {
                                                rules: [{
                                                    required: this.state.type == OperatorConstant.saveAndApproval ? false :  this.state.require_memo, message: '请输入备注！',
                                                }],
                                                initialValue: dataSource.approvalmemo
                                            })(
                                                <Input disabled={approvalDisable}/>

                                            )}
                                        </FormItem>
                                    </Col>
                                </Row>
                            </TabPane>
                            <TabPane tab="审核记录" key="2">
                                <Row>
                                    <Col>
                                        <div>
                                            <Table dataSource={this.props.approvalList} columns={this.columns} bordered={true} size={'middle'} pagination={pagination} scroll={{ x: true}}/>
                                        </div>
                                    </Col>
                                </Row>
                            </TabPane>
                        </Tabs>
                        : ""}

                </Form>
            </Modal>
        );
	}
})

